import { Effect, ImmerReducer, Reducer, Subscription } from 'umi';

export interface SocketModelState {
  receiveList: Array<any>;
  socket: any;
}

export interface SocketModelType {
  namespace: 'socket';
  state: SocketModelState;
  effects: {
    query: Effect;
  };
  reducers: {
    // save: Reducer<SocketModelState>;
    // 启用 immer 之后
    changeReceiveList: ImmerReducer<SocketModelState>;
    setSocket: ImmerReducer<SocketModelState>;
  };
  subscriptions: { setReceiveList: Subscription };
}

const SocketModel: SocketModelType = {
  namespace: 'socket',

  state: {
    receiveList: [],
    socket: '',
  },

  effects: {
    *query({ payload }, { call, put }) {},
  },
  reducers: {
    // save(state, action) {
    //   return {
    //     ...state,
    //     ...action.payload,
    //   };
    // },
    // 启用 immer 之后
    changeReceiveList(state, action) {
      state.receiveList = action.data;
    },
    setSocket(state, action) {
      state.socket = action.socket;
    },
  },
  subscriptions: {
    setReceiveList({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        if (pathname === '/') {
          dispatch({
            type: 'query',
          });
        }
      });
    },
  },
};

export default SocketModel;
